<!--
 * @Descripttion: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2021-12-10 16:03:47
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2021-12-13 14:17:13
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>翻转二叉树</title>
</head>

<body>
    <script>
        // 将二叉树的每个节点的左右分支翻转过来，左变成右，右变成左
        var vertTree = function (root) {
            //递归前序实现二叉树遍历
            const invertNode = function (left, right) {
                let temp = left;
                left = right;
                right = temp;
                root.left = left;
                root.right = right;
            }

            // 确定递归函数的参数和返回值
            if (root === null) {
                return root;
            }
            // 确定交换逻辑
            invertNode(root.left, root.right);
            vertTree(root.left);
            vertTree(root.right);
            return root;
        }

        // 使用迭代版本的前序遍历
        var invertTree = function (root) {
            const invertNode = function (root, left, right) {
                let temp = left;
                left = right;
                right = temp;
                root.left = left;
                root.right = right;
            }
            let stack = [];
            if (root === null) {
                return root;
            }
            stack.push(root);
            while (stack.length) {
                let node = stack.pop();
                if (root != null) {
                    node.right && stack.push(node.right);
                    node.left && stack.push(node.left);
                    stack.push(node);
                    stack.push(null);
                } else {
                    node = stack.pop();
                    invertNode(node, node.left, node.right);
                }
            }
            return root;
        }


        //层序遍历
        var invertTree = function (root) {
            const invertNode = function (root, left, right) {
                let temp = left;
                left = right;
                right = temp;
                root.left = left;
                root.right = right;
            }
            //层序遍历
            let stack = [];
            if (root == null) {
                return root;
            }
            stack.push(root);
            while (stack.length) {
                let length = queue.length;
                while (length--) {
                    let node = queue.shift();
                    invertNode(node, node.left, node.right);
                    node.left && stack.push(node.left);
                    node.right && stack.push(node.right);
                }
            }
            return root;
        }




    </script>
</body>

</html>